<?php

namespace app\demo\controller;

use my\JElasticV2;
use think\facade\Db;

/**
 * 本页需要安装 elasticsearch
 *
 */
class Elastic extends Base
{

    // 查询
    private function search()
    {
        $param = request()->param();
        $title = $param['title'] ?? '';
        $desc = $param['desc'] ?? '';
        $content = $param['content'] ?? '';
        $index = 'book';
        $es = new JElasticV2();
        $must = [];
        if($title) {
            $must[] = ['match_phrase' => [ 'title' => $title ]];
        }
        if($desc) {
            $must[] = ['match_phrase' => [ 'desc' => $desc ]];
        }
        if($content) {
            $must[] = ['match_phrase' => [ 'content' => $content ]];
        }
        $res = $es->search($index,[
            'bool' => [
                'must' => $must,
                'filter' => [
//                            'range' => [
//                                'id' => ['gt' => 0]
//                            ]
                ]
            ]
        ],['id','title','desc','content']);
        if (isset($res['error'])) {
            mylog($this->cmd, var_export($res, true), 'elastic.log');
            pp($res['error']['reason']);
        } else {
            $list = $res['hits']['hits'];
            pp($list);
        }
    }

    // 全文检索创建更新表结构及数据 - 临时用(数据量小的时候)
    private function createBookIndex()
    {
        $param = request()->param();
        $force = $param['force'] ?? 0;
        $index = 'book';
        $properties = [
            'id' => [
                'type' => 'integer',
            ],
            'title' => [
                'type' => 'text',
            ],
            'desc' => [
                'type' => 'text'
            ],
            'content' => [
                'type' => 'text'
            ],
        ];
        try {
            $es = new JElasticV2();
            if (intval($force) === 1) { // 强制更新索引结构[表结构发生变化时]
                $es->deleteIndex($index);
                pp('deleteIndex success');
            }
            $index_exist = $es->getIndex($index);
            if ($index_exist === false) {
                $es->createIndex($index, $properties);
                pp('createIndex success!');
            } else {
                pp('index already exist!');
            }
            $list = Db::connect('psn')->table('mp_article')->where(true)->select()->toArray();
            foreach ($list as $row) {
                $es->setDoc($index,$row); // 201新增 200修改
            }
        } catch (\Exception $e) {
            mylog($this->cmd, $e->getMessage(), 'elastic.log');
            pp($e->getMessage());
            exit('error');
        }
        pp('success createBookDetailIndex');
    }



}
